<?php


namespace app\admin\controller;


use app\admin\validate\GoodsValidate;
use app\admin\validate\IDMustBePositiveInt;
use app\service\model\AttributeModel;
use app\service\model\CategoryModel;
use app\service\model\GoodsModel;
use app\service\Tree;
use app\service\Y;
use think\Request;

class Goods extends BaseAdmin
{
    /**
     * 商品列表
     * @param Request $request
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DbException
     */
    public function index(Request $request) {
        $where = [];
        if ($name = input('param.name', '')) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }
        $data = GoodsModel::with(['category', 'images'])
            ->where($where)
            ->order(['sort' => 'desc', 'id'=>'desc'])
            ->paginate([
            'list_rows'=> input('param.limit', 10),
            'query' => input('param.')
        ])->toArray();
        return Y::table($data['data'], $data['total']);
    }

    /**
     * 商品数据
     * @param Request $request
     * @param GoodsValidate $goods_validate
     * @return \think\response\Json
     * @throws \app\service\exception\ParameterException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save(Request $request, GoodsValidate $goods_validate): \think\response\Json
    {
        $id = input('param.id', 0);
        if ($request->isPost()) {

            $goods_validate->goCheck();
            $param = $goods_validate->getDataByRule();

            if ($param['price'] > $param['market_price']) {
                // 单规格商品
                return Y::error('销售价不能高于市场价');
            }
            $param['sales'] = input('param.sales', 0);

            return GoodsModel::saveGoods($param, $id);
        }
        $data = [];
        $attrs = '';
        if ($id > 0) {
            $data = GoodsModel::with(['images', 'content'])->find($id);
            $attrs = json_encode($data->sku->toArray());
        }
        $attribute = AttributeModel::select();
        if ($data) {
            $sku_attr_ids = array_unique(explode(',', implode(',', $data->sku()->column('attrs'))));
            foreach ($attribute as &$v) {
                if (in_array($v->id, $sku_attr_ids)) {
                    $v['checked'] = 1;
                }
            }
        }

        $attribute = Tree::unlimitForLayer(AttributeModel::select());
        $categories = CategoryModel::select();
        $categories = Tree::unlimitForLevel($categories);

        return Y::success(compact('data', 'categories', 'attribute', 'attrs'));
    }

    /**
     * 获取商品属性
     * @param IDMustBePositiveInt $IDMustBePositiveInt
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_attrs(IDMustBePositiveInt $IDMustBePositiveInt) {
        $IDMustBePositiveInt->goCheck();
        $id = input('param.id');
        $goods = GoodsModel::find($id);
        if ($goods)
            return Y::success(['sku' => $goods->sku, 'attrs' => implode(',', $goods->sku()->column('attrs'))], '商品sku');
        else
            return Y::error('商品不存在');
    }

    /**
     * 删除数据
     * @param IDMustBePositiveInt $IDMustBePositiveInt
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete(IDMustBePositiveInt $IDMustBePositiveInt) {
        $IDMustBePositiveInt->goCheck();
        $id = input('param.id');
        return $this->deleteDate((new GoodsModel()), $id);
    }

    /**
     * 修改排序
     * @param IDMustBePositiveInt $IDMustBePositiveInt
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save_sort(IDMustBePositiveInt $IDMustBePositiveInt) {
        $IDMustBePositiveInt->goCheck();
        $id = input('param.id');
        $data = GoodsModel::find($id);
        if ($data) {
            $data->save(['sort' => input('param.value', 0)]);
        }

        return Y::success([], '修改成功');
    }

    /**
     * 修改状态
     * @param IDMustBePositiveInt $IDMustBePositiveInt
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save_status(IDMustBePositiveInt $IDMustBePositiveInt) {
        $IDMustBePositiveInt->goCheck();
        $id = input('param.id');
        $data = GoodsModel::find($id);
        if ($data) {
            $data->save(['status' => input('param.value', 0)]);
        }
        return Y::success([], '修改成功');
    }
}